﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Runtime.Caching;
using Abp.UI;
using AVISOutBound.SSOServer.Dto;
using AVISOutBound.SSOServer.VerifyCode.Dto;

namespace AVISOutBound.SSOServer.VerifyCode
{
    public class ValidateCodeAppService : SSOServerAppServiceBase, IValidateCodeAppService
    {
        private readonly ICacheManager _cacheManager;
        public ValidateCodeAppService(ICacheManager cacheManager)
        {
            _cacheManager = cacheManager;
        }
        public ValidateCodeDto CreateValidateCode()
        {
            ValidateCode vCode = new ValidateCode();
            string code = vCode.CreateValidateCode(5);
            byte[] bytes = vCode.CreateValidateGraphic(code);
            string imgId = Guid.NewGuid().ToString();
            _cacheManager.GetCache(SSOServerConsts.CacheVerifyCodeStringName).Set(imgId, code, null, new TimeSpan(0, 1, 0));
            return new ValidateCodeDto { ImgId = imgId, ImgFile = Convert.ToBase64String(bytes) };
        }

        public bool CheckValidateCode(string phone, string code)
        {
            var _code = _cacheManager.GetCache(SSOServerConsts.CacheVerifyCodeStringName).GetOrDefault(phone);
            if (_code == null)
                return false;
            else
                return _code.ToString() == code;
        }

        public string GetValidateCode(string phone)
        {
            return _cacheManager.GetCache(SSOServerConsts.CacheVerifyCodeStringName).GetOrDefault(phone) as string;
        }

        public bool SendSmsCode(string phone)
        {
            ValidateCode vCode = new ValidateCode();
            string code = vCode.CreateValidateCode(5);

            var cache = _cacheManager.GetCache(SSOServerConsts.CacheSmsCode);
            _cacheManager.GetCache(SSOServerConsts.CacheSmsCode).Set(phone, code, null, new TimeSpan(0, 1, 0));
            return true;
        }

        public bool CheckSmsCode(string phone, string code)
        {
            var _code = _cacheManager.GetCache(SSOServerConsts.CacheSmsCode).GetOrDefault(phone);
            if (_code == null)
                return false;
            else
                return _code.ToString() == code;
        }

        public string GetSmsCode(string phone)
        {
            return _cacheManager.GetCache(SSOServerConsts.CacheSmsCode).GetOrDefault(phone) as string;
        }

        #region Private
        private const String KeyPrefix = "SMS_";
        private const int KeyExpireTime = 5;

        /// <summary>
        /// 获取随机6位字符
        /// </summary>
        /// <returns></returns>
        private String GetRamdonCode()
        {
            Random generator = new Random();
            String code = generator.Next(0, 999999).ToString("D6");
            return code;
        }
        #endregion
    }
}
